package com.zhonghan.common.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * 获取请求路径和参数
 * @author zhangceven
 *
 */
public class UrlAndParamsFilter implements Filter {
	
	/**
	 * 初始化过滤器
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("UrlParamsFilter过滤器初始化...");
	}

	/**
	 * 执行过滤
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest)request;
		
		String uri = req.getRequestURI()+ (req.getQueryString() == null ? "" : "?"+ req.getQueryString());
		
		System.out.print("请求方式\t" + req.getMethod() + " 请求路径:\t" + uri);
		
        Map map = new HashMap();
        
        Enumeration paramNames = req.getParameterNames();
        
        while (paramNames.hasMoreElements()) {
        	
        	String paramName = (String) paramNames.nextElement();
         
        	String[] paramValues = req.getParameterValues(paramName);
        	
        	if (paramValues.length == 1) {
        		
        		String paramValue = paramValues[0];
        		
        		if (paramValue.length() != 0) {
        			
        			System.out.print("\t参数:\t" + paramName + " = " + paramValue);
        			
        			map.put(paramName, paramValue);
        			
        		}
        	}
       }
        
       System.out.println(""); // 换行
       
       request = (ServletRequest)req;
       
       chain.doFilter(request, response);
		
	}

	/**
	 * 执行销毁
	 */
	@Override
	public void destroy() {
		System.out.println("UrlParamsFilter过滤器销毁...");
	}


}
